<?php
// 应用公共文件
use PHPMailer\PHPMailer\PHPMailer;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Sms\V20210111\SmsClient;
use think\cache\driver\Redis;
use think\facade\Cache;
use think\facade\Db;
use think\Request;

function show($code, $message = "error", $data = [], $httpStatus = 200)
{
    $result = [
        'code' => $code,
        'msg' => $message,
        'result' => $data,
    ];
    return json($result, $httpStatus);
}

//公共请求key value Redis
function GetRedis($key, $num = 1)
{
    $redis = new Redis();
    $redis->connect("127.0.0.1", "6379");
    $redis->select($num);
    $model = $redis->get($key);
    return $model;
}

//公共修改key value Redis
function SetRedis($key, $value, $num = 1)
{
    $redis = new Redis();
    $redis->connect("127.0.0.1", "6379");
    $redis->select($num);
    $res = $redis->set($key, $value);
    if (!$res) {
        return false;
    }
    return true;
}

function getRemainderTime($one_time, $two_time, $return_type = 0, $format_array = array('年', '月', '日', '时', '分', '秒'))
{
    if ($return_type < 0 || $return_type > 6) {
        return false;
    }
    if (!is_int($one_time) && !is_int($two_time)) {
        return false;
    }
    $remainder_seconds = abs($one_time - $two_time);
    //年
    $years = 0;
    if (($return_type == 0 || $return_type == 6) && $remainder_seconds - 31536000 > 0) {
        $years = floor($remainder_seconds / (31536000));
    }
    //月
    $monthes = 0;
    if (($return_type == 0 || $return_type >= 5) && $remainder_seconds - $years * 31536000 - 2592000 > 0) {
        $monthes = floor(($remainder_seconds - $years * 31536000) / (2592000));
    }
    //日
    $days = 0;
    if (($return_type == 0 || $return_type >= 4) && $remainder_seconds - $years * 31536000 - $monthes * 2592000 - 86400 > 0) {
        $days = floor(($remainder_seconds - $years * 31536000 - $monthes * 2592000) / (86400));
    }
    //时
    $hours = 0;
    if (($return_type == 0 || $return_type >= 3) && $remainder_seconds - $years * 31536000 - $monthes * 2592000 - $days * 86400 - 3600 > 0) {
        $hours = floor(($remainder_seconds - $years * 31536000 - $monthes * 2592000 - $days * 86400) / 3600);
    }
    //分
    $minutes = 0;
    if (($return_type == 0 || $return_type >= 2) && $remainder_seconds - $years * 31536000 - $monthes * 2592000 - $days * 86400 - $hours * 3600 - 60 > 0) {
        $minutes = floor(($remainder_seconds - $years * 31536000 - $monthes * 2592000 - $days * 86400 - $hours * 3600) / 60);
    }
    //秒
    $seconds = $remainder_seconds - $years * 31536000 - $monthes * 2592000 - $days * 86400 - $hours * 3600 - $minutes * 60;
    $return = false;
    switch ($return_type) {
        case 0:
            if ($years > 0) {
                $return = $years . $format_array[0] . $monthes . $format_array[1] . $days . $format_array[2] . $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
            } else if ($monthes > 0) {
                $return = $monthes . $format_array[1] . $days . $format_array[2] . $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
            } else if ($days > 0) {
                $return = $days . $format_array[2] . $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
            } else if ($hours > 0) {
                $return = $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
            } else if ($minutes > 0) {
                $return = $minutes . $format_array[4] . $seconds . $format_array[5];
            } else {
                $return = $seconds . $format_array[5];
            }
            break;
        case 1:
            $return = $seconds . $format_array[5];
            break;
        case 2:
            $return = $minutes . $format_array[4] . $seconds . $format_array[5];
            break;
        case 3:
            $return = $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
            break;
        case 4:
            $return = $days . $format_array[2] . $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
            break;
        case 5:
            $return = $monthes . $format_array[1] . $days . $format_array[2] . $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
            break;
        case 6:
            $return = $years . $format_array[0] . $monthes . $format_array[1] . $days . $format_array[2] . $hours . $format_array[3] . $minutes . $format_array[4] . $seconds . $format_array[5];
            break;
        default:
            $return = false;
    }
    $data['day'] = $days;
    $data['hours'] = $hours;
    $data['minutes'] = $minutes;
    $data['seconds'] = $seconds;
    return $data;
}

function curl_get($url, &$httpCode = 0)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //不做证书校验,部署在linux环境下请改为true
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $file_contents;
}

function doCurl($url, $type = 0, $data = [])
{
    $ch = curl_init(); // 初始化
    // 设置选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    if ($type == 1) {
        // post
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    //执行并获取内容
    $output = curl_exec($ch);
    // 释放curl句柄
    curl_close($ch);
    return $output;
}

function getRandChar($length)
{
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;

    for (
        $i = 0;
        $i < $length;
        $i++
    ) {
        $str .= $strPol[rand(0, $max)];
    }
    return $str;
}

//获取今日剩余时间秒数
function End_time()
{
    $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
    return $endToday - time();
}

//根据ip获取城市
function city($ip)
{
    $secretId = config('tengxunMap.secretId');
    // 云市场分配的密钥Key
    $secretKey = config('tengxunMap.secretKey');
    $source = 'market';

    // 签名
    $datetime = gmdate('D, d M Y H:i:s T');
    $signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
    $sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
    $auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);

    // 请求方法
    $method = 'GET';
    // 请求头
    $headers = array(
        'X-Source' => $source,
        'X-Date' => $datetime,
        'Authorization' => $auth,
    );
    // 查询参数
    $queryParams = array(
        'ip' => $ip,
    );
    // body参数（POST方法下）
    $bodyParams = array();
    // url参数拼接
    $url = 'https://service-jr977f7k-1301115409.gz.apigw.tencentcs.com/release/';
    if (count($queryParams) > 0) {
        $url .= '?' . http_build_query($queryParams);
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
        return $k . ': ' . $v;
    }, array_values($headers), array_keys($headers)));
    if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
    }

    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        $detail['nation'] = '未知';
        $detail['region'] = '未知';
        $detail['city'] = '未知';
        return $detail;
    } else {
        $res = json_decode($data, true);
        if ($res['message'] != "Success") {
            $detail['nation'] = '未知';
            $detail['region'] = '未知';
            $detail['city'] = '未知';
            return $detail;
        } else {
            //            return $res;
            $detail['nation'] = $res['data']['nation'];
            $detail['region'] = !empty($res['data']['details']['region']) ? $res['data']['details']['region'] : '未知';
            $detail['city'] = !empty($res['data']['details']['city']) ? $res['data']['details']['city'] : '未知';
            return $detail;
        }
    }
    curl_close($ch);
}

//获取日期订单编号
function get_no($id, $join_id)
{
    return $id . date("His", time()) . $join_id;
}

function getAccessToken()
{
    $token_url = sprintf(config('wx.token_url'), config('wx.app_id'), config('wx.app_secret'));
    //写入缓存a
    $access_token = Cache::get('access_token');
//    $redis = new Redis();
//    $redis->connect("127.0.0.1", "6379");
//    $access_token = $redis->get('access_token');
    if ($access_token) {
        return $access_token;
    } else {
        //
        $result = curl_get($token_url);
        $wxResult = json_decode($result, true);
        Cache::set('access_token', $wxResult['access_token'], 7200);
//        $res = $redis->set('access_token', $wxResult['access_token']);
//        $redis->expire('access_token', 7200);
        return $wxResult['access_token'];
    }
}

/**\
 * 推送消息
 */
function open_message($openid, $activity_id, $title, $name, $num)
{
    //先去获取token
    $token = getAccessToken();
    $wxSendUrl = sprintf(config('wx.send_url'), $token);
    $arr = [
        'access_token' => $token,
        "touser" => $openid,
        'template_id' => config('wx.open_template_id'),
        'page' => '/pages/prizeDrawDetail/index?id=' . $activity_id,
        'miniprogram_state' => 'formal',
        'data' => [
            'thing1' => [
                'value' => $title
            ],
            'thing7' => [
                'value' => $name
            ],
            'number9' => [
                'value' => $num,
            ],
            'thing4' => [
                'value' => '点击查看详情'
            ],
        ],
    ];
    $json = json_encode($arr, true);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $wxSendUrl);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // curl_setopt($ch, CURL_SSLVERSION_SSL, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $reponse = json_decode(curl_exec($ch));
    curl_close($ch);
}

/**\
 * 推送消息
 */
function open_message_issue($openid, $activity_id, $name)
{
    //先去获取token
    $token = getAccessToken();
    $wxSendUrl = sprintf(config('wx.send_url'), $token);
    $arr = [
        'access_token' => $token,
        "touser" => $openid,
        'template_id' => config('wx.template_id'),
        'page' => '/pages/prizeDraw/index',
        'miniprogram_state' => 'formal',
        'data' => [
            'thing1' => [
                'value' => $name
            ],
            'time4' => [
                'value' => date("H:i", time()),
            ],
        ],
    ];
    $json = json_encode($arr, true);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $wxSendUrl);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // curl_setopt($ch, CURL_SSLVERSION_SSL, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $reponse = json_decode(curl_exec($ch));
    curl_close($ch);
}

/**\
 * 推送消息
 */
function open_message_regret($openid, $activity_id, $name, $code)
{
    //先去获取token
    $token = getAccessToken();
    //    dd($token);
    //    $token="45_0N7XwVkP_iw0L1tql-v019tIOjkeTVNsDg-MwaUgB3fbN_ZwEc3o2Bjuo2MMycB4JF_Sk4BwagcK9ZfzWbdpeHzjJrwZUL-EmCk1epO3G0h1txyaqxVDAwhW3Cg4yiVGGnH7ZeUW54c0txyDPFEjABAGWV";
    $wxAppId = config('wx.app_id');
    $wxAppSecret = config('wx.app_secret');
    $wxSendUrl = sprintf(config('wx.send_url'), $token);
    $arr = [
        'access_token' => $token,
        "touser" => $openid,
        'template_id' => config('wx.open_template_id'),
        'page' => '/pages/luckyDetail/index?id=' . $activity_id,
        'miniprogram_state' => 'formal',
        'data' => [
            'thing10' => [
                'value' => $name
            ],
            'character_string19' => [
                'value' => $code
            ],
            'date5' => [
                'value' => date("H:i", time()),
            ],
            'thing18' => [
                'value' => '很遗憾未中奖去参加其他抽奖'
            ],
        ],
    ];
    $json = json_encode($arr, true);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $wxSendUrl);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // curl_setopt($ch, CURL_SSLVERSION_SSL, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $reponse = json_decode(curl_exec($ch));
    curl_close($ch);
}

/**
 * 获取邀请好友的二维码
 */
function get_wx_invite_qr_code($user_id)
{
    //先去获取token
    $token = getAccessToken();
    //    dd($token);
    // $token = "48_j09uyfrWXlSla7O4e8E9YLC1U8EbP3mK-bW-zxglB91QdCwy5RXL5O2r1UEMWM91cX-DR-S9vHeLEicq-5g6AElR5iZqIu-d3hVqZ_Uq2LpdtMvEkpFRUeVwIECDGES4TLwYLS0sOhiuPnrMDTSgAAAKAZ";
    $wxSendUrl = sprintf(config('wx.get_wx_invite_qr_code'), $token);
    $arr = [
        'scene' => $user_id,
//        'is_hyaline'=>true
    ];
    $json = json_encode($arr, true);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $wxSendUrl);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // curl_setopt($ch, CURL_SSLVERSION_SSL, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $res = curl_exec($ch);
    $img = './qr_code/' . $user_id . '.jpg';
    $img_path = "/qr_code/" . $user_id . '.jpg';
    $r = file_put_contents($img, $res);
    $request = request();
    return $request->domain() . $img_path;
}

function id_card($type = 1)
{
    if ($type == 1) {
        $id_card = intval(Db::name('zoon')
            ->max('id_card'));
        if (!$id_card) {
            return 100001;
        }
        $id_card = ($id_card + 1);
//        $name="chicken".date("Ymd").rand(100,999);
    }
    return $id_card;
//    return $name;
}

function floatMoney($cost)
{
    return floatval(sprintf("%.2f", round($cost, 2)));
}

/**\
 * 查询快递
 */
function address_index($no, $code)
{
    //参数设置
    $key = config('kd100.key');                        // 客户授权key
    $customer = config('kd100.customer');                   // 查询公司编号
    $param = array(
        'com' => $code,             // 快递公司编码
        'num' => $no,     // 快递单号
        'phone' => '',                // 手机号
        'from' => '',                 // 出发地城市
        'to' => '',                   // 目的地城市
        'resultv2' => '1',            // 开启行政区域解析
        'show' => '0',                // 返回格式：0：json格式（默认），1：xml，2：html，3：text
        'order' => 'desc'             // 返回结果排序:desc降序（默认）,asc 升序
    );

    //请求参数
    $post_data = array();
    $post_data['customer'] = $customer;
    $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
    $sign = md5($post_data['param'] . $key . $post_data['customer']);
    $post_data['sign'] = strtoupper($sign);

    $url = config('kd100.url');    // 实时查询请求地址
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $result = curl_exec($ch);
    // 第二个参数为true，表示格式化输出json
    $data = json_decode($result, true);
    return $data;
}

/**\
 * 查询天气
 */
function weather($city = "北京")
{
    $apiUrl = 'http://apis.juhe.cn/simpleWeather/query';
// 请求参数
    $params = [
        'city' => $city, // 要查询的城市
        'key' => 'd0ce2f0fe6289ec40a0e24a6678795cd'
    ];
    $paramsString = http_build_query($params);

// 发起接口网络请求
    $response = doCurl($apiUrl, 1, $paramsString);
    $result = json_decode($response, true);
    if ($result) {
        $errorCode = $result['error_code'];
        if ($errorCode == 0) {
            // 获取返回的天气相关信息，具体根据业务实际逻辑调整修改
            $data = $result['result'];
            $datas['wendu'] = $data['realtime']['temperature'];
            $datas['shidu'] = $data['realtime']['humidity'];
            $datas['tianqi'] = $data['realtime']['info'];
            return $datas;
            // 打印当前实况天气信息
            echo "当前城市：{$data["city"]}" . PHP_EOL;
            echo "当前温度：{$data["realtime"]["temperature"]}" . PHP_EOL;
            echo "当前湿度：{$data["realtime"]["humidity"]}" . PHP_EOL;
            echo "当前天气：{$data["realtime"]["info"]}" . PHP_EOL;
            echo "当前风向：{$data["realtime"]["direct"]}" . PHP_EOL;
            echo "当前风力：{$data["realtime"]["power"]}" . PHP_EOL;
            echo "当前空气质量：{$data["realtime"]["aqi"]}" . PHP_EOL;

        } else {
            // 请求异常
            echo "请求异常:{$errorCode}_{$result["reason"]}" . PHP_EOL;
        }
    } else {
        // 可能网络异常等问题，无法正常获得相应内容，业务逻辑可自行修改
        echo "请求异常" . PHP_EOL;
    }
}

function checkHex($image)
{
    if (file_exists($image)) {
        $resource = fopen($image, 'rb');
        $fileSize = filesize($image);
        fseek($resource, 0);
        if ($fileSize > 512) { // 若文件大于521B文件取头和尾
            $hexCode = bin2hex(fread($resource, 512));
            fseek($resource, $fileSize - 512);
            $hexCode .= bin2hex(fread($resource, 512));
        } else { // 取全部
            $hexCode = bin2hex(fread($resource, $fileSize));
        }
        fclose($resource);

        if (preg_match("/(3c25.*?28.*?29.*?253e)|(3c3f.*?28.*?29.*?3f3e)|(3C534352495054)|(2F5343524950543E)|(3C736372697074)|(2F7363726970743E)/is", $hexCode))
            return false;
        else
            return true;
    } else {
        return false;
    }
}

//发送验证码
function tx_send_sms($phone, $code, $tll)
{
    try {
        //控制台 >API密钥管理页面获取 SecretID 和 SecretKey
        $cred = new Credential(config('wx.secretId'), config('wx.secretKey'));
        //实例化一个http选项 [可选]
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("sms.tencentcloudapi.com");
        //实例化一个client选项 [可选]
        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        /**
         * 实例化以sms为例的client对象, [第三个参数 可选]
         *
         * 第二个参数是地域信息,可以直接填 ap-guangzhou
         */
        $client = new SmsClient($cred, "ap-guangzhou", $clientProfile);
        // 实例化一个sms发送短信请求对象,每个接口都会对应一个request对象。
        $req = new SendSmsRequest();
        //生成随机验证码
        $params = array(
            //接收方手机号，带上+86 示例：+8613711112222
            "PhoneNumberSet" => ['+86' . $phone],
            //短信应用ID:在 [短信控制台] 添加应用后生成的实际SdkAppId
            "SmsSdkAppId" => config('wx.SmsSdkAppId'),
            //短信签名内容:[不理解可以看文章里的截图]
            "SignName" => config('wx.SignName'),
            //模板ID:必须填写已审核通过的模板
            "TemplateId" => config('wx.TemplateId'),
            //模板参数:若无模板参数，则设置为空
            //我的模板中有两个参数 第一个是验证码参数 第二个是有效时间
            "TemplateParamSet" => array((string)$code, '5')
        );
        $req->fromJsonString(json_encode($params));
        //发出请求，返回一个实例
        $resp = $client->SendSms($req);
        dd(123);
        dd($resp);
        //如果成功，把验证码存入缓存
        //成功实例中的Code值为 Ok
        if ($resp->SendStatusSet[0]->Code === "Ok") {
            $code_res = Cache::set($phone . "code", "是否频繁发送", 60);
            $code = Cache::set($phone, $code, $tll);
            return show(1, '发送成功');
        }
    } catch (TencentCloudSDKException $e) {
        return show(0, $e);
    }
}

/**
 * 腾讯云通过isbn码获取书籍信息
 */
function isbn_query($isbn)
{

    $secretId = 'AKID1kr1cn05uGe1u0p98B7wuBYEkd25K8anT72v';
// 云市场分配的密钥Key
    $secretKey = '94q9DWf93mDbWN96myop8WW3MNknP0lPmGFwhpXZ';
    $source = 'market';

// 签名
    $datetime = gmdate('D,d M Y H:i:s T');
    $signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
    $sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
    $auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);

// 请求方法
    $method = 'POST';
// 请求头
    $headers = array(
        'X-Source' => $source,
        'X-Date' => $datetime,
        'Authorization' => $auth,

    );
// 查询参数
    $queryParams = array();
// body参数（POST方法下）
    $bodyParams = array(
        'isbn' => $isbn,
    );
// url参数拼接
    $url = 'https://service-ed62t9xo-1305308687.gz.apigw.tencentcs.com/release/isbn/query';
    if (count($queryParams) > 0) {
        $url .= '?' . http_build_query($queryParams);
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
        return $k . ': ' . $v;
    }, array_values($headers), array_keys($headers)));
    if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
    }

    $data = curl_exec($ch);
//        curl_close($ch);
    if (curl_errno($ch)) {
        return false;
    } else {
        curl_close($ch);
        //获取完存储到数据库里
        $book = \Qiniu\json_decode($data, true);
        if ($book['code'] == 200) {
            return $book['data'];
        } else {
            return false;
        }
    }

}

/**\
 * @param $month
 * @param $day
 * @return string
 * 通过月和日期返回星座
 */
function get_xingzuo($month, $day)
{
    $xingzuo = '';
    // 检查参数有效性
    if ($month < 1 || $month > 12 || $day < 1 || $day > 31) {
        return '';
    }
    if (($month == 1 && $day >= 20) || ($month == 2 && $day <= 18)) {
        $xingzuo = "水瓶座";
    } else if (($month == 2 && $day >= 19) || ($month == 3 && $day <= 20)) {
        $xingzuo = "双鱼座";
    } else if (($month == 3 && $day >= 21) || ($month == 4 && $day <= 19)) {
        $xingzuo = "白羊座";
    } else if (($month == 4 && $day >= 20) || ($month == 5 && $day <= 20)) {
        $xingzuo = "金牛座";
    } else if (($month == 5 && $day >= 21) || ($month == 6 && $day <= 21)) {
        $xingzuo = "双子座";
    } else if (($month == 6 && $day >= 22) || ($month == 7 && $day <= 22)) {
        $xingzuo = "巨蟹座";
    } else if (($month == 7 && $day >= 23) || ($month == 8 && $day <= 22)) {
        $xingzuo = "狮子座";
    } else if (($month == 8 && $day >= 23) || ($month == 9 && $day <= 22)) {
        $xingzuo = "处女座";
    } else if (($month == 9 && $day >= 23) || ($month == 10 && $day <= 23)) {
        $xingzuo = "天秤座";
    } else if (($month == 10 && $day >= 24) || ($month == 11 && $day <= 22)) {
        $xingzuo = "天蝎座";
    } else if (($month == 11 && $day >= 23) || ($month == 12 && $day <= 21)) {
        $xingzuo = "射手座";
    } else if (($month == 12 && $day >= 22) || ($month == 1 && $day <= 19)) {
        $xingzuo = "摩羯座";
    }
    return $xingzuo;
}

function get_age($birthday)
{
    list($year, $month, $day) = explode("-", $birthday);
    // date() 函数 里面填 Y。。。。  直接转化当前时间
    $year_diff = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff = date("d") - $day;
    if ($day_diff < 0 || $month_diff < 0) {
        $year_diff--;
    }
    if ($year_diff==-1){
        return '';
    }
    return $year_diff;
}

function get_week($time = "", $format = "Y-m-d")
{
    $time = $time != '' ? $time : time();
    //获取当前周几
    $week = date("w", $time);
    $data = [];
    for ($i = 1; $i <= 7; $i++) {
        $data[] = [
            'day' => date($format, strtotime("+" . $i - $week . ' days', $time)),
            'week' => date('w', strtotime("+" . $i - $week . ' days', $time))
        ];

//        $data[]['week']=
    }
    return $data;
}

function get_this_week()
{
    $first_day = strtotime('this week Monday');
    $last_day = strtotime('this week Sunday');
//    $start_day=date("d",$first_day);
//    $end_day=date("d",$last_day);
    $data = [];
    for ($i = $first_day; $i <= $last_day; $i += 86400) {
        $data[] = [
            'day' => date("d", $i),
            'week' => date("w", $i),
        ];
    }
    return $data;
}

//增加经验值
function add_empirical($userId, $type,$num=1)
{
//    $num=0;
    $astrict=1;//1不限制2限制次数
    switch ($type){
        case 2:
            $num=10;
            break;
        case 4:
            $num=1;
            $astrict=2;
            break;
        case 5:
            $num=2;
            $astrict=2;
            break;
    }
    $result['user_id'] = $userId;
    $result['number'] = $num;
    $result['type'] = $type;
    $result['create_time'] = time();
    $result['update_time'] = time();
    if ($astrict == 1) {
        $res=Db::name('user_empirical_list')
            ->insert($result);
        if (!$res){
            return false;
        }
        return true;
    }else{
        //判断今日已经有多少次了
        //找到存储在redis的数据
        $redis=Cache::get($userId."_".$type);
        if ($redis<5){
            //小于五再进行下面的操作
            $res=Db::name('user_empirical_list')
                ->insert($result);
            if (!$res){
                return false;
            }
            //修改redis的次数
            Cache::set($userId."_".$type,$redis+1,strtotime('23:59:59')-time());
            return true;
        }
    }
}
if (!function_exists('get_hide_phone')){
    function get_hide_phone($phone){
        $hiddenPhone = substr_replace($phone, '****', 3, 4);
        return $hiddenPhone;
    }
}
if (!function_exists('getDaysInYear')){
    function getDaysInYear($year){
        if (($year % 4 === 0 && $year % 100!== 0) || ($year % 400 === 0)) {
            return 366;
        }
        return 365;
    }
}
if (!function_exists('get_level')){
    function get_level($num){
        if ($num<=5){
            return 1;
        }
        if ($num>5&&$num<=10){
            return 2;
        }
        if ($num>10&&$num<=20){
            return 3;
        }
        if ($num>20&&$num<=30){
            return 4;
        }
        if ($num>30){
            return 5;
        }
    }
}
if (!function_exists('get_level_name')){
    function get_level_name($num){
        if ($num<=5){
            $name="轻度烟瘾";
            $wenan="戒烟较容易,无明显戒断反应";
        }
        if ($num>5&&$num<=10){
            $name="中度烟瘾";
            $wenan="戒烟可控制,戒烟时有轻微不适";
        }
        if ($num>10&&$num<=20){
            $name="中重度烟瘾";
            $wenan="已产生较强心理依赖,戒烟时明显戒断反应";
        }
        if ($num>20&&$num<=30){
            $name="重度烟瘾";
            $wenan="戒烟困难,戒断反应强烈且易复吸";
        }
        if ($num>30){
            $name="极重度烟瘾";
            $wenan="烟瘾严重影响生活和健康,戒断反应极为严重";
        }
        $data['name']=$name;
        $data['wenan']=$wenan;
        return $data;
    }
}
if (!function_exists('get_diff_day')){
    function get_diff_day($timestamp1,$timestamp2){

// 计算两个时间戳的差值（秒）
        $diffInSeconds = abs($timestamp2 - $timestamp1);

// 将秒转换为天
        $days = $diffInSeconds / (60 * 60 * 24);

// 由于除法结果是小数，可能需要取整或四舍五入
        $days = ceil($days); // 取整到下一位整数（如果是向下取整）
// 或者使用round()进行四舍五入
// $days = round($days);
        return $days;
    }
}
if (!function_exists('get_smoke_age')){
    function get_smoke_age($time){
       if ($time==0){
           return 0;
       }else{
           $timestamp1 = $time; // 例如，2000年1月1日
           $timestamp2 = time(); // 当前时间的时间戳

// 将时间戳转换为DateTime对象
           $datetime1 = new DateTime("@$timestamp1");
           $datetime2 = new DateTime("@$timestamp2");

// 使用date_diff计算差异
           $interval = $datetime1->diff($datetime2);

// 获取年份差异
           $years = $interval->y;
           return $years;
       }
    }
}
if (!function_exists('get_invite_code')){
    function get_invite_code(){
        $y=date("y");
        $now=new DateTime();
        $yearStart=new DateTime($now->format('Y-01-01'));
        $interval = $now->diff($yearStart); // 计算两个日期之间的差异
        $d = $interval->days + 1;
        $d = sprintf("%03d", $d);
        //再去找到今天的新增
        $today=Cache::get('today_new_user_num');
        if (!$today){
            $c=1;
            //去新增
            $todayEnd = strtotime('tomorrow') - 1;

// 获取当前时间的时间戳
            $now = time();

// 计算今日剩余时间戳
            $remainingTime = $todayEnd - $now;

            Cache::set('today_new_user_num',2,$remainingTime);
        }else{
            $c=$today;

            //去新增
            $num=$today+1;
            $todayEnd = strtotime('tomorrow') - 1;

// 获取当前时间的时间戳
            $now = time();

// 计算今日剩余时间戳
            $remainingTime = $todayEnd - $now;

            Cache::set('today_new_user_num',$num,$remainingTime);
        }
        $c = sprintf("%03d", $c);
        return $y.$d.$c;
    }
if (!function_exists('sendMailFile')){
    function sendMailFile($to_email, $to_name,$file,$subject){
        $body = "<p>尊敬的用户: <br>
您好! <br>
您于".date("Y-m-d H:i:s",time())."在火因记申请导出的数据已成功处理。本次导出的数据已整理为XLS格式的附件，方便您进行查看与后续的分析使用。<br>
感谢您对我们APP的支持与信任!<br>".date("Y-m-d",time())."<br></p>";
        try {
            $mail = new PHPMailer(true);
            $mail->CharSet = 'UTF-8';
            $mail->isSMTP();
            $mail->Host = config('mail.send_service');  // 替换为实际的SMTP服务器地址
            $mail->SMTPAuth = true;
            $mail->Username = config('mail.name');  // 发件人邮箱账号
            $mail->Password = config('mail.password');  // 发件人邮箱密码
            $mail->SMTPSecure = config('mail.send_SMTPSecure');  // 可以根据服务器情况选择tls或ssl
            $mail->Port = config('mail.send_port');  // 对应SMTPSecure的端口号

            // 发件人信息
            $mail->setFrom(config('mail.name'), '火因记');

            // 收件人信息（可以循环添加多个收件人）
            $mail->addAddress($to_email, $to_name);
            $mail->Timeout = 180;
            // 邮件主题
            $mail->Subject = $subject;

            // 邮件内容（支持HTML格式）
            $mail->isHTML(true);
            $mail->Body = $body;
            $mail->addAttachment($file);
            // 发送邮件
            $mail->send();
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
}
if (!function_exists('sendLoginCode')){
        function sendLoginCode($to_email, $to_name,$subject,$code){
            $body = "<p>尊敬的火因记用户: <br>
您好! <br>
您的验证码是<br>".$code."<br>有效期5分钟</p>";
            try {
                $mail = new PHPMailer(true);
                $mail->CharSet = 'UTF-8';
                $mail->isSMTP();
                $mail->Host = config('mail.send_service');  // 替换为实际的SMTP服务器地址
                $mail->SMTPAuth = true;
                $mail->Username = config('mail.name');  // 发件人邮箱账号
                $mail->Password = config('mail.password');  // 发件人邮箱密码
                $mail->SMTPSecure = config('mail.send_SMTPSecure');  // 可以根据服务器情况选择tls或ssl
                $mail->Port = config('mail.send_port');  // 对应SMTPSecure的端口号

                // 发件人信息
                $mail->setFrom(config('mail.name'), '火因记');

                // 收件人信息（可以循环添加多个收件人）
                $mail->addAddress($to_email, $to_name);
                $mail->Timeout = 180;
                // 邮件主题
                $mail->Subject = $subject;

                // 邮件内容（支持HTML格式）
                $mail->isHTML(true);
                $mail->Body = $body;
                // 发送邮件
                $mail->send();
                return true;
            } catch (\Exception $e) {
                return false;
            }
        }
    }
function get_month(){
    return date('j');
}
    function get_last_month(){
        $currentDate = new DateTime();
// 将日期设置为上个月
        $lastMonth = clone $currentDate;
        $lastMonth->modify('last month');

// 获取上个月的年份和月份
        $year = $lastMonth->format('Y');
        $month = $lastMonth->format('n');

// 使用 cal_days_in_month 函数获取上个月的天数
        $daysInLastMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
        return $daysInLastMonth;
    }
}
function get_shangsheng_xiajiang($one,$two){
    //上升是2,下降是3
    if ($one==$two){
        $arrows=1;
    }elseif ($one>$two){
        $arrows=2;
    }else{
        $arrows=3;
    }
    return $arrows;
}
function get_report_wenan($data){
    // 统计数组中每个元素出现的次数
    $counts = array_count_values($data);
    // 找出出现次数最多的个数
    $maxCount = max($counts);
    reset($counts);
    $num=key($counts);
    //1夸赞,2愤怒
    $icon=1;
    if ($maxCount==1){
        $wenan1="上周数据基本持平,继续保持";
        $wenan2="一条数据有所上升";
        $icon=2;
    }elseif ($maxCount==2){
        if ($num==1){
            $wenan1="上周数据基本持平,继续保持";
            $wenan2="两条数据基本持平";
            $icon=1;
        }elseif($num==2){
            $wenan1="上周数据有所上升,控制烟量";
            $wenan2="二条数据有所上升";
            $icon=2;
        }else{
            $wenan1="上周数据有所下降,继续保持";
            $wenan2="二条数据有所下降";
            $icon=1;
        }
    }else{
        if ($num==1){
            $wenan1="上周数据基本持平,继续保持";
            $wenan2="三条数据基本持平";
            $icon=1;
        }elseif($num==2){
            $wenan1="上周数据有所上升,控制烟量";
            $wenan2="三条数据有所上升";
            $icon=2;
        }else{
            $wenan1="上周数据有所下降,继续保持";
            $wenan2="三条数据有所下降";
            $icon=1;
        }
    }
    $result['wenan1']=$wenan1;
    $result['wenan2']=$wenan2;
    $result['icon']=$icon;
    return $result;
}
function generateOrderNumber() {
    // 生成一个 UUID
    $uuid =\Ramsey\Uuid\Uuid::uuid4();
    // 去除 UUID 中的横杠
    $orderNumber = str_replace('-', '', $uuid->toString());
    return $orderNumber;
}
function juheSend($mobile,$code){

// 聚合数据短信 API 请求地址
$apiUrl = 'http://v.juhe.cn/sms/send';

// 替换为你自己在聚合数据申请的 APPKEY
$appKey = '422e8913e6765cba0fbf75bcd17c15cf';

// 短信模板 ID，需要在聚合数据平台申请
$tplId = '268639';
$time=5;
// 模板中的变量，格式为 JSON 字符串，根据模板内容修改
$tplValue = "#code#=".$code."&#m#=5";
// 接收短信的手机号码

// 构建请求参数
$params = [
    'key' => $appKey,
    'mobile' => $mobile,
    'tpl_id' => $tplId,
    'tpl_value' => $tplValue
];

// 将参数拼接成 URL 查询字符串
$paramString = http_build_query($params);

// 初始化 cURL 会话
$ch = curl_init();

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, $apiUrl . '?' . $paramString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// 执行 cURL 请求
$response = curl_exec($ch);;

// 检查是否有 cURL 错误
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}

// 关闭 cURL 会话
curl_close($ch);

// 解析响应结果
$result = json_decode($response, true);
// 根据响应结果进行处理
if ($result && $result['error_code'] == 0) {
    $code_res = Cache::set($mobile . "code", "是否频繁发送", 60);
    $code = Cache::set($mobile.$code,$code, 300);
    return show(1,'发送成功');
} else {
    if ($result) {
        echo '短信发送失败，错误码：' . $result['error_code'] . '，错误信息：' . $result['reason'];
        return show(0,'发送失败');
    } else {
        echo '请求失败，无法解析响应结果';
    }
}

}
function getCycleInfo($checkinCount) {
    if ($checkinCount <= 0) {
        return ['days' => [
            ['day'=>1,'status'=>'incomplete'],
            ['day'=>2,'status'=>'incomplete'],
            ['day'=>3,'status'=>'incomplete'],
            ['day'=>4,'status'=>'incomplete'],
            ['day'=>5,'status'=>'incomplete'],
            ['day'=>6,'status'=>'incomplete'],
            ['day'=>7,'status'=>'incomplete'],
        ]];
    }

    // 计算当前周期和日期范围
    $currentCycle = ceil($checkinCount / 7);
    $startDay = ($currentCycle - 1) * 7 + 1;
    $endDay = $currentCycle * 7;

    // 生成周期内7天数据
    $days = [];
    for ($day = $startDay; $day <= $endDay; $day++) {
        $status = 'incomplete'; // 默认未完成

        if ($day < $checkinCount) {
            $status = 'completed'; // 已完成
        } elseif ($day == $checkinCount) {
            $status = 'active';    // 当前激活状态
        }

        $days[] = [
            'day' => $day,
            'status' => $status
        ];
    }

    return [
        'days' => $days
    ];
}
function get_device($userAgent){
    if (stripos($userAgent, 'iPhone') !== false || stripos($userAgent, 'iPad') !== false) {
        $device="苹果";
    }elseif(stripos($userAgent, 'Android') !== false){
        $device="安卓";
    }else{
        $device="小程序";
    }
    return $device;
}